package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.BusinessFileInfo;
import cn.wizzer.app.bus.modules.services.BusinessFileInfoService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.PageUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.app.web.modules.controllers.open.file.UploadController;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@IocBean
@At("/platform/bus/report_template/")
public class ReportTemplateController {

    private static final Log log = Logs.get();

    @Inject
    private BusinessFileInfoService businessFileInfoService;
    @Inject
    private SysDictService sysDictService;

    @At("")
    @Ok("beetl:/platform/bus/configManagement/reportTemplate/index.html")
    @RequiresPermissions("bus.config_management.report_template")
    public void index(HttpServletRequest req) {
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
        req.setAttribute("templateNameOptions", JSONArray.fromObject(sysDictService.dictCodeTree("templateName")));
        req.setAttribute("yplxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("yplx")));

    }

    @At
    @Ok("json:full")
    @RequiresPermissions("bus.config_management.report_template.data")
    public Object data(
            @Param("pageNumber") int pageNumber,
            @Param("pageSize") int pageSize,
            @Param("pageOrderName") String pageOrderName,
            @Param("pageOrderBy") String pageOrderBy,
            @Param("reportTemplateName") String reportTemplateName,
            @Param("pType") String pType
    ) {
        try {
            String sql ="select b.*,u.username from  bus_file_info b left join sys_user u on b.opBy = u.id  where b.delFlag=0 and b.infoType = 'template' ";

            if(StringUtils.isNotBlank(reportTemplateName)){
                sql+=" and b.infoName like '%"+reportTemplateName+"%' ";
            }
            if(StringUtils.isNotBlank(pType)){
                sql+=" and (b.productType like '"+pType+"%' or b.productType like '%-"+pType+"%') ";
            }
            sql+=StringUtil.dataScopeFilter("b");
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc,b.opAt desc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc,b.opAt desc ";
                }
            }else{
                sql+= " order by b.opAt desc ";
            }
            return Result.success().addData(businessFileInfoService.listPage(pageNumber, pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.config_management.report_template.add")
    @SLog(tag = "添加模板文件", msg = "模板名称:${businessFileInfo.infoName}")
    public Object addDo(@Param("..") BusinessFileInfo businessFileInfo, HttpServletRequest req) {
        try {
            String productTypes = Strings.trim(businessFileInfo.getProductType());
            if (!Strings.isEmpty(productTypes)) {
                List<BusinessFileInfo> list = businessFileInfoService.listEntity(
                        Sqls.create("select b.id,b.productType,b.fileBeforeName,u.username as opBy from bus_file_info b " +
                                " left join sys_user u on b.opBy = u.id " +
                                " where b.infoName = '"+Strings.trim(businessFileInfo.getInfoName())+"'  and b.delFlag = 0"));
                String[] LproductType = productTypes.split("-");
                for (BusinessFileInfo b : list) {
                    if (StringUtils.isNotBlank(b.getProductType())) {
                        List<String> types = Arrays.stream(b.getProductType().split("-")).collect(Collectors.toList());
                        //List<String> typeList = Stream.concat( Arrays.stream(types),Arrays.stream(LproductType)).distinct().collect(Collectors.toList());

                        List<String> typeList = Arrays.stream(LproductType).filter(item -> types.contains(item)).collect(Collectors.toList());

                        if (typeList.size() > 0) {
                            return Result.error("类型已经绑定模板了，文件名为：" + b.getFileBeforeName() + "，创建人为：" + b.getOpBy()).addData(typeList);
                        }
                    }
                }
            }
            businessFileInfo.setInfoName(Strings.trim(businessFileInfo.getInfoName()));
            businessFileInfo.setInfoVersion(Strings.trim(businessFileInfo.getInfoVersion()));
            businessFileInfo.setInfoType("template");
            businessFileInfo.setRemark(Strings.trim(businessFileInfo.getRemark()));
            businessFileInfo.setOpBy(StringUtil.getPlatformUid());
            businessFileInfo.setOperatorName(StringUtil.getPlatformUsername());
            businessFileInfo.setDisabled(false);
            businessFileInfoService.insert(businessFileInfo);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }
    @At
    @Ok("json")
    @RequiresPermissions("bus.config_management.report_template.edit")
    @SLog(tag = "修改模板文件", msg = "模板名称:${businessFileInfo.infoName}")
    public Object editDo(@Param("..") BusinessFileInfo businessFileInfo, HttpServletRequest req) {
        try {
            BusinessFileInfo businessFileInfoOld = businessFileInfoService.fetch(businessFileInfo.getId());
            if(!businessFileInfoOld.getFilePath().equals(businessFileInfo.getFilePath())){
                //删除旧的模板文件
                String uploadPath = this.getUploadPathConfig();
                File file = new File(uploadPath+businessFileInfoOld.getFilePath());
                if (file.exists()) {
                    file.delete();
                }
            }
            businessFileInfo.setOpBy(StringUtil.getPlatformUid());
            businessFileInfo.setOperatorName(StringUtil.getPlatformUsername());
            businessFileInfo.setDisabled(false);
            businessFileInfoService.update(businessFileInfo);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/detail/?")
    @Ok("json")
    @RequiresPermissions("bus.config_management.report_template.detail")
    public Object detail(String reportTemplateId, HttpServletRequest req) {
        try {
            BusinessFileInfo businessFileInfo = businessFileInfoService.fetch(reportTemplateId);
            return Result.success(businessFileInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/enable/?")
    @Ok("json")
    @RequiresPermissions("bus.config_management.report_template.edit")
    @SLog(tag = "启用模板", msg = "模板ID:${args[1].getAttribute('templateId')}")
    public Object enable(String reportTemplateId, HttpServletRequest req) {
        try {
            req.setAttribute("templateId", reportTemplateId);
            businessFileInfoService.update(Chain.make("disabled", false), Cnd.where("id", "=", reportTemplateId));
            businessFileInfoService.deleteCache(reportTemplateId);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/disable/?")
    @Ok("json")
    @RequiresPermissions("bus.config_management.report_template.edit")
    @SLog(tag = "禁用模板", msg = "模板ID:${args[1].getAttribute('templateId')}")
    public Object disable(String reportTemplateId, HttpServletRequest req) {
        try {
            req.setAttribute("templateId", reportTemplateId);
            businessFileInfoService.update(Chain.make("disabled", true), Cnd.where("id", "=", reportTemplateId));
            businessFileInfoService.deleteCache(reportTemplateId);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/delete/?")
    @Ok("json")
    @RequiresPermissions("bus.config_management.report_template.delete")
    @SLog(tag = "删除模板", msg = "模板ID:${args[1].getAttribute('templateId')}")
    public Object delete(String reportTemplateId, HttpServletRequest req) {
        try {
            //逻辑删除
            req.setAttribute("templateId", reportTemplateId);
            businessFileInfoService.vDelete(reportTemplateId);
            businessFileInfoService.clearCache();
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }
    private String getUploadPathConfig() throws Exception {
        String uploadPath;
        //系统没开启配置,上传到项目路径
        if ("false".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))) {
            uploadPath = UploadController.class.getClassLoader().getResource("").getPath() + "upload";
        } else if (
                ("true".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))) && (Globals.MyConfig.getOrDefault("ConfigUploadPath", null) != null)
        ) {
            uploadPath = Globals.MyConfig.get("ConfigUploadPath").toString();
        } else {
            throw new Exception("文件上传路径配置有误");
        }
        return uploadPath;
    }
}
